package exttable.timetable.ttpanels;

import dbutils.DbUtils;
import dbutils.StringQueries;
import exttable.testversioning.tablemodel.TestVersioningModel;
import exttable.testversioning.testversionrunner.TestVersionsEditor;
import exttable.testversioning.testversionrunner.TestVersionsRenderer;
import exttable.timetable.ETestType;
import exttable.timetable.models.AnalysCheckerTableModel;
import exttable.timetable.models.AnalysisModel;
import exttable.timetable.models.VisitModel;
import exttable.view.ViewAnalysis;
import exttable.view.ViewType;
import exttable.view.ViewVersion;
import utils.Localisation;

import javax.swing.*;
import java.awt.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: Apr 11, 2010
 * Time: 5:34:45 PM
 * To change this template use File | Settings | File Templates.
 */
public class AnalysisFillerPanel {

    private JTable analysisTable;
    private JTable objectDataTable;
    private JTable sideEffectsTable;
    private JTable[] tableArray = new JTable[3];
    private JTable[] visitAnalysisArray = new JTable[3];

    public AnalysisFillerPanel() {
        this.analysisTable = new JTable();
        this.objectDataTable = new JTable();
        this.sideEffectsTable = new JTable();
        tableArray[0] = analysisTable;
        tableArray[1] = objectDataTable;
        tableArray[2] = sideEffectsTable;
    }

    public JPanel initTabPanels() {
        analysisTable.setModel(new TestVersioningModel(true, true, true, ETestType.ANALYS, true));
        analysisTable.setName(ETestType.ANALYS.name());
        analysisTable.getColumnModel().getColumn(2).setCellRenderer(new TestVersionsRenderer());
        analysisTable.getColumnModel().getColumn(2).setCellEditor(new TestVersionsEditor());

        objectDataTable.setModel(new TestVersioningModel(true, true, true, ETestType.OBJECT_DATA, true));
        objectDataTable.setName(ETestType.OBJECT_DATA.name());
        objectDataTable.getColumnModel().getColumn(2).setCellRenderer(new TestVersionsRenderer());
        objectDataTable.getColumnModel().getColumn(2).setCellEditor(new TestVersionsEditor());

        sideEffectsTable.setModel(new TestVersioningModel(true, true, true, ETestType.SIDE_EFFECTS, true));
        sideEffectsTable.setName(ETestType.SIDE_EFFECTS.name());
        sideEffectsTable.getColumnModel().getColumn(2).setCellRenderer(new TestVersionsRenderer());
        sideEffectsTable.getColumnModel().getColumn(2).setCellEditor(new TestVersionsEditor());

        JPanel toReturn = new JPanel();
        toReturn.setLayout(new BorderLayout());
        Component selectType = new JLabel(Localisation.getMessage("timetable.selecttest"));
        Container top = new JPanel(new FlowLayout());
        JPanel testSelection = new JPanel(new FlowLayout());
        testSelection.add(new JTable());
        top.add(selectType);


        JTabbedPane pane = new JTabbedPane();
        int i = 0;
        for (ETestType res : ETestType.values()) {
            pane.add(getAnalysisTypes(res).toString(), new JScrollPane(tableArray[i]));
            i++;
        }

        toReturn.add(top, BorderLayout.NORTH);
        toReturn.add(pane, BorderLayout.CENTER);
        toReturn.setPreferredSize(new Dimension(750, 400));
        return toReturn;
    }

    private static ViewType getAnalysisTypes(ETestType dicType) {

        ViewType tt = null;
        try {
            PreparedStatement ps = DbUtils.getDBConnectionGeneral().prepareStatement(StringQueries.TEST_TYPE);
            ps.setString(1, dicType.name());
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                tt = new ViewType.Build().type(rs.getString("id"))
                        .nameEn(rs.getString("name_en"))
                        .nameRu(rs.getString("name_ru"))
                        .nameKz("name_kk")
                        .build();
            }
            ps.close();
            return tt;
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new IllegalStateException();
        }

    }

    private String getAnalysisVersion(ViewAnalysis va, ViewVersion version) {
        PreparedStatement ps;
        try {
            String toReturn = null;
            ps = DbUtils.getDBConnectionGeneral().prepareStatement(StringQueries.ANALYSIS_VERSION_KEY);
            ps.setInt(1, va.getAnalysisId());
            ps.setString(2, version.getVersionId());
            ResultSet rs = ps.executeQuery();
//            System.out.println(" VER: " + version.getVersionId());
            while (rs.next()) {
                toReturn = rs.getString("analysis_version_key");
            }
            return toReturn;
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new IllegalStateException();
        }
    }

    public List<AnalysisModel> getCheckAnalysis(JTable table) {
        if (table.getCellEditor() != null) {
            table.getCellEditor().stopCellEditing();
        }
        List<AnalysisModel> toReturn = new ArrayList<AnalysisModel>();
        for (int i = 0; i < table.getModel().getRowCount(); i++) {
            if (Boolean.valueOf(table.getModel().getValueAt(i, 1).toString()) && isVersionSelected(table.getModel().getValueAt(i, 2))) {
                AnalysisModel am = new AnalysisModel();
                ViewAnalysis va = (ViewAnalysis) table.getModel().getValueAt(i, 0);
                ViewVersion vv = (ViewVersion) table.getModel().getValueAt(i, 2);
//                System.out.println("V: " + vv.getVersionId());
                va.setAnalysisVersionKey(getAnalysisVersion(va, vv));

//                System.out.println("VA R ID: " + va.getAnalysisId());
//                System.out.println("VA R V: " + va.getAnalysisVersionKey());
                am.setCarried(true);
                am.setAnalysis(va);
//                am.setVersion(vv);
                toReturn.add(am);
            }
        }
        return toReturn;
    }

    private boolean isVersionSelected(Object valueAt) {
        ViewVersion vv = (ViewVersion) valueAt;

        if (vv.getVersionId().equals("0")) {
//            System.out.println("works");
            JOptionPane.showMessageDialog(null, Localisation.getMessage("error.noversionselected"),
                    Localisation.getMessage("warring.waring"), JOptionPane.WARNING_MESSAGE);
            return false;
        } else {
            return true;
        }

    }

    public JPanel analysisPanelValidator(Vector<VisitModel> visits) {

        final Map<ETestType, List<AnalysisModel>> mapAnalysis = new HashMap<ETestType, List<AnalysisModel>>(3);
        mapAnalysis.clear();
        for (JTable table : tableArray) {
            mapAnalysis.put(ETestType.valueOf(table.getName()), getCheckAnalysis(table));
        }
        return mapAnalysisVisits(mapAnalysis, visits);
    }

    public JPanel mapAnalysisVisits(Map<ETestType, List<AnalysisModel>> mapAnalysis, Vector<VisitModel> visits) {

        JPanel toReturn = new JPanel();
        JTabbedPane tabPanel = new JTabbedPane();
        int i = 0;
        for (Map.Entry<ETestType, List<AnalysisModel>> res : mapAnalysis.entrySet()) {
            if (res.getValue().size() > 0) {
                JTable table = new JTable(new AnalysCheckerTableModel(res.getValue(), visits));
                visitAnalysisArray[i] = table;
                table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                table.setName(res.getKey().name());
                JScrollPane js = new JScrollPane();
//                js.setSize(new Dimension(950, 400));
                js.setViewportView(table);
                tabPanel.add(getAnalysisTypes(res.getKey()).toString(), js);
                i++;
            }
        }
        toReturn.add(tabPanel);
//        toReturn.setPreferredSize(new Dimension(750, 400));
        return toReturn;
    }


    public JTable[] getVisitAnalysisArray() {
        return visitAnalysisArray;
    }
}
